package com.jasiri.project.ui.credit.page

import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.jasiri.project.R
import com.jasiri.project.adapter.AmountAdapter
import com.jasiri.project.adapter.CreditRepayLableAdapter
import com.jasiri.project.databinding.PageRepayBinding
import com.jasiri.project.pro.ProFragment
import com.jasiri.project.utils.config.Configs
import com.jasiri.project.utils.event.EventType
import com.jasiri.project.utils.event.track.TrackEventManager
import com.jasiri.project.utils.http.AppUrls
import com.jasiri.project.utils.http.AppUrls.addCommonParams
import com.jasiri.project.utils.http.IHttpCallback
import com.jasiri.lib.baseadapter.JasiriOnItemChildClickListener
import org.greenrobot.eventbus.EventBus
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Sikadwa
 * @Author wwdeng
 * @CreateTime: 2024/5/22 17:44
 * @Annotation：待还款
 */
class RepayPage: ProFragment() {
    private var _binding: PageRepayBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "Cannot access binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var mAmountAdapter: AmountAdapter? = null
    //还款明细
    private var mLableAdapter: CreditRepayLableAdapter? = null
    //是否展开
    private var isOpen = false

    override fun getRootView(inflater: LayoutInflater): View {
        _binding = PageRepayBinding.inflate(inflater)
        return binding.root
    }

    override fun initView() {
        _binding?.parentLayout?.setPadding(0, com.jasiri.project.utils.BarUtils.getStatusBarHeight(),0,0)
        initRefreshView()
        initRvAmount()
        initRvRepayListView()
        showOpenOrCloseView()
    }

    override fun initListener() {
        _binding?.imgUser?.setOnClickListener {
            showPersonalDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_USER,"CreditRepayment Page")
        }
        _binding?.imgKefu?.setOnClickListener {
            showKefuDialog("CreditRepayment Page")
            addEvent(EventType.CLICK.CLICK_CUSTOMER,"CreditRepayment Page")
        }
        //展开、收起
        _binding?.ivLable?.setOnClickListener {
            isOpen = !isOpen
            showOpenOrCloseView()
        }
        //还款
        _binding?.btnRepayment?.setOnClickListener {
            TrackEventManager.trackEventNow(EventType.CLICK.CLICK_CREDIT_REPAYMENT,"")
            showLoading()
            onPayAction()
        }
    }

    override fun initData() {
        showLoading()
        loadCreditRepayInfoAction()
        addEvent(EventType.PAGE.PAGE_CREDIT_REPAYMENT_START,"")
    }

    fun refreshAction(){
        loadCreditRepayInfoAction()
    }

    /* 初始化刷新 */
    private fun initRefreshView() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(Configs.Event.PROCESS_REFRESH)

            loadCreditRepayInfoAction()
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    private fun initRvAmount(){
        _binding?.rvAmount?.setHasFixedSize(true)
        _binding?.rvAmount?.isNestedScrollingEnabled = false
        _binding?.rvAmount?.isFocusableInTouchMode = false //不需要焦点
        val decoration = com.jasiri.project.utils.DensityUtils.dp2px(14f)
        _binding?.rvAmount?.addItemDecoration(
            com.jasiri.project.utils.rv.LinearDecoration(
                0,
                decoration,
                0,
                0
            )
        )
        val layoutManager = LinearLayoutManager(getContext())
        layoutManager.orientation = RecyclerView.HORIZONTAL
        _binding?.rvAmount?.layoutManager = layoutManager
        mAmountAdapter = AmountAdapter(_binding?.rvAmount)
        mAmountAdapter?.setOnItemChildClickListener { parent, childView, position ->
            val item = this.mAmountAdapter?.getItem(position)
        }
        _binding?.rvAmount?.adapter = mAmountAdapter
    }

    /**
     * 初始化列表
     */
    private fun initRvRepayListView() {
        _binding?.rvRepayInfo?.setHasFixedSize(true)
        _binding?.rvRepayInfo?.isNestedScrollingEnabled = false
        _binding?.rvRepayInfo?.isFocusableInTouchMode = false //不需要焦点
        _binding?.rvRepayInfo?.layoutManager = LinearLayoutManager(context)
//        val topDecoration = DensityUtils.dp2px(8f)
//        _binding?.rvRepayInfo?.addItemDecoration(LinearDecoration(0,0,topDecoration,topDecoration))
        mLableAdapter = CreditRepayLableAdapter(_binding?.rvRepayInfo)
        _binding?.rvRepayInfo?.adapter = mLableAdapter
        _binding?.rvRepayInfo?.itemAnimator = DefaultItemAnimator()
        mLableAdapter?.setOnItemChildClickListener(JasiriOnItemChildClickListener { _, childView, position ->
        })
    }

    /**
     * 收起
     */
    private fun showOpenOrCloseView(){
        if (isOpen){//展开
            _binding?.rvRepayInfo?.visibility = View.VISIBLE
            _binding?.ivLable?.setImageResource(R.mipmap.img_credit_repay_up_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_OPEN,"")
        } else {
            _binding?.rvRepayInfo?.visibility = View.GONE
            _binding?.ivLable?.setImageResource(R.mipmap.img_credit_repay_down_icon)
            addEvent(EventType.CLICK.CLICK_CREDIT_REPAYMENT_INFO_CLOSE,"")
        }
    }

    /**
     * 设置还款信息
     */
    @SuppressLint("SetTextI18n")
    fun setRepaymentInfo(data: JSONObject) {
        val amountList = arrayListOf<String>()
        val amountString = BigDecimal(data.optString("amount")).stripTrailingZeros().toPlainString()
        for (i in amountString.indices){
            amountList.add(amountString[i].toString())
        }
        mAmountAdapter?.data = amountList

        _binding?.textRepayAmount?.text = data.optString("repayAmount") + " " + data.optString("currency")
        _binding?.textRepayDate?.text = data.optString("repayDate")
        _binding?.textTotal?.text = data.optString("repayAmount")
        _binding?.textUnit?.text = data.optString("currency")

//        val jsArray = data.optJSONArray("repayList")
        val jsArray = data.optJSONArray("detailItemList")
        val dataList = arrayListOf<JSONObject>()
        if (jsArray != null) {
            for (i in 0..<jsArray.length()){
                dataList.add(jsArray.optJSONObject(i))
            }
        }
        mLableAdapter?.data = dataList
    }

    /**
     * 跳转支付H5
     */
    private fun enterPayLink(payUrl: String){
        val uri = Uri.parse(payUrl)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
    }

    /**
     * 获取还款信息
     */
    private fun loadCreditRepayInfoAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_INFO)
            put("oldFlag","YES")
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    //某些地区没有repayList，需要手动添加数据
                    if (!it.has("repayList") || it.optJSONArray("repayList") == null){
                        val unit = it.optString("currency")
                        val repayArray = JSONArray()
                        val amountItem = JSONObject()
                        amountItem.put("showName",getString(R.string.credit_repaylist_loan_amount))
                        amountItem.put("showDetail",it.optString("amount") + unit)
                        repayArray.put(amountItem)

                        val interestItem = JSONObject()
                        interestItem.put("showName",getString(R.string.credit_repaylist_interest))
                        interestItem.put("showDetail",it.optString("interest") + unit)
                        repayArray.put(interestItem)

                        val serviceFee = BigDecimal(it.optString("serviceFee")).stripTrailingZeros().toPlainString()
                        if (serviceFee.toDouble() > 0){
                            val serviceFeeItem = JSONObject()
                            serviceFeeItem.put("showName",getString(R.string.credit_repaylist_service_fee))
                            serviceFeeItem.put("showDetail",it.optString("serviceFee") + unit)
                            repayArray.put(serviceFeeItem)
                        }

                        val overdueDayItem = JSONObject()
                        overdueDayItem.put("showName",getString(R.string.credit_repaylist_overdue_days))
                        overdueDayItem.put("showDetail",String.format(getString(R.string.credit_repaylist_days),it.optString("overdueDay")))
                        repayArray.put(overdueDayItem)

                        val overduePenaltyItem = JSONObject()
                        overduePenaltyItem.put("showName",getString(R.string.credit_repaylist_overdue_penalty))
                        overduePenaltyItem.put("showDetail",it.optString("overdueAmount") + unit)
                        repayArray.put(overduePenaltyItem)
                        it.put("repayList",repayArray)
                    }
                    setRepaymentInfo(it)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
                _binding?.refreshLayout?.finishRefresh()
            }
        })
    }

    /**
     * 还款
     */
    private fun onPayAction(){
        val httpUrl = AppUrls.getHttpUrl(AppUrls.URL.COMMON)
        val params = JSONObject().addCommonParams().apply {
            put("path", AppUrls.PATH.CREDIT_REPAYMENT_URL)
        }
        postAction(httpUrl,params,object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                obj?.let {
                    var repayUrl = it.optString("repayUrl","")
                    if (repayUrl.isEmpty()){
                        repayUrl = it.optString("url")
                    }
                    enterPayLink(repayUrl)
                }
            }
            override fun onRequestError(error: JSONObject) {
            }
            override fun onRequestFinish() {
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        //退出待还款页面立即上报所有埋点
        TrackEventManager.trackEventNow(EventType.PAGE.PAGE_CREDIT_REPAYMENT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}